﻿/*-------------------------------------------------------------------
* 依懒于miniUI,jQuery,jQuery.action
* 作者：江怀玉
* 用途：用于处理前端的datagrid/treegrid通用功能操作事件方法
* 
* 
* 
---------------------------------------------------------------------*/
var fnGetSelectedRow = function () {
    var row = grid.getSelected();
    return row;
}

var fnGetSelectedRows = function () {
    var rows = grid.getSelecteds();
    return rows;
}
///新增
var fnAdd = function () {
    if (typeof (fnCustomAdd) != "undefined") {
        fnCustomAdd();
        return;
    }
    mini.open({
        url: "/ExtendPage/editview/DefineEditForm.aspx?entity=" + const_EditEntity + "&functionid=" + const_functionId + "&id=",
        title: "新增" + const_PageTitle, width: _openWindowWidth, height: _openWindowHeight,
        onload: function () {
            //var iframe = this.getIFrameEl();
            //var data = { action: "new" };
            //iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            grid.reload();
        }
    });
}
//
var fnEdit = function () {
    if (typeof (fnCustomEdit) != "undefined") {
        fnCustomEdit();
        return;
    }
    var row = fnGetSelectedRow();
    //debugger
    if (row) {
        mini.open({
            url: "/ExtendPage/editview/DefineEditForm.aspx?entity=" + const_EditEntity + "&functionid=" + const_functionId + "&id=" + row[const_entityID],
            title: "编辑" + const_PageTitle, width: _openWindowWidth, height: _openWindowHeight,
            onload: function () {
                //var iframe = this.getIFrameEl();
                //var data = { action: "edit", id: row.id };
                //iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
                grid.reload();

            }
        });

    } else {
        alert("请选中一条记录");
    }
}

///-------------------------------------------
///快速搜索
///-------------------------------------------
var fnQuciklyQuery = function () {

    if (const_QueryField == undefined || const_QueryField == "") {
        return;
    }
    var _keyword = document.getElementById("QueryContext").value;
    if (_keyword == "") {
        return;
    }
    var _chk = document.getElementById("checkAndOr").checked;
    //alert(_chk);
    var _opr = _chk ? " and " : " or ";
    //alert(_opr);
    var _fields = const_QueryField.split(",");
    var _keys = _keyword.split(" ");
    var _condition = "";
    for (n = 0; n < _keys.length; n++) {
        if (_keys[n] == "") {
            continue;
        }
        if (n == 0) {
            _condition = " ( "
        }
        else {
            _condition = _condition + _opr + " ( ";
        }
        for (i = 0; i < _fields.length; i++) {
            if (i == 0) {
                _condition = _condition + " (" + _fields[i] + " like '%" + _keys[n] + "%')  ";
            }
            else {
                _condition = _condition + " or (" + _fields[i] + " like '%" + _keys[n] + "%')  ";
            }
        }
        _condition = _condition + " )";
    }
    //alert(_condition);
    grid.setUrl("../data/jsondata.aspx?entity=" + const_entityName + "&condition=" + encodeURI(_condition) + "&order" + const_Order + "&datagrid=true");
    grid.load(); //{ condition:_condition});//mini.encode(_condition)
}
/***-------------------------------通用查询功能---------------------------***/
function showQuery() {
    $("#QueryItem").show(1000);
}

function fnQuery() {
    showQuery();
}

function fnCloseQuery() {
    $("#QueryItem").hide(1000);
}

function fnEmptyQuery() {
    var items = $("#QueryItem").find("input");
    $.each(items, function (index) {
        $(items[index]).val("");
    }
   );

}
/*-----------------------------/

------------------------------*/
function fnHightLevelQuery() {
    fnQueryRec("QueryItem");
}

function fnQueryRec(id) {
    var _linkchar = "and";
    //$("#QueryItem").hide(1000);
    var condition = " 1=1 ";
    var items = $("#" + id).find("div[id^=query_item_]");
    $.each(items, function (index) {
        var item = items[index];
        var eq = $(item).find("select").val();
        var _field = $(item).attr("id").replace("query_item_", "");
        var ctrls = $(item).find("input[class*=mini]"); //表示样式含有mini信息的
        var _value = $(ctrls[0]).val();
        if ($(ctrls[0]).attr("class").indexOf("check") > 0) {
            _value = _value == "on" ? "1" : "0";
        }
        var c = "";
        if (_value != "") {
            if (ctrls.length < 2) {
                if (eq.indexOf("like") > -1) {
                    c = _field + " " + eq + " '%" + _value + "%' ";
                }
                else {
                    c = _field + " " + eq + " '" + _value + "' ";
                }
            }

            else {
                _value2 = $(ctrls[1]).val();
                if (_value2 != "") {
                    c = _field + " between '" + _value + "'  and  '" + _value2 + "'";
                }
                else {
                    c = _field + " " + eq + " '" + _value + "' ";
                }
            }
            if (c != "") {
                condition = condition == "" ? c : condition + " " + _linkchar + " " + c;
            }
        }
    });
    //alert( encodeURI(condition));
    grid.setUrl("../data/jsondata.aspx?entity=" + const_entityName + "&condition=" + encodeURI(condition) + "&order" + const_Order + "&datagrid=true");
    grid.load();
}
/******************************************************************************************/

//停用
var fnSetStop = function () {
    if (typeof (fnCustomSetStop) != "undefined") {
        fnCustomSetStop();
        return;
    }
    fnUpdateSingleFieldAction("is_stop", 1);
}


//上传文件
var fnUploadFile = function () {
    if (typeof (fnCustomUploadFile) != "undefined") {
        fnCustomUploadFile();
        return;
    }
    //var row = fnGetSelectedRow();
    mini.open({
        url: "/extendpage/upload/uploadfile.aspx?entity=" + const_EditEntity + "&functionid=" + const_functionId + "&action=importdata&id=",
        title: "上传文件" + const_PageTitle, width: 450, height: 300,
        onload: function () {
            //var iframe = this.getIFrameEl();
            //var data = { action: "new" };
            //var data = iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.fnGetData();
                alert(data);
            }
        }
    });
}

//通用单字段更新数据方法
var fnUpdateSingleFieldAction = function (field, value) {
    var rows = fnGetSelectedRows();
    var id = "";
    if (rows.length > 0) {
        if (confirm("确定删除选中记录？")) {
            var ids = [];
            for (var i = 0, l = rows.length; i < l; i++) {
                var r = rows[i];
                ids.push(r[const_entityID]);
            }
            id = ids.join(',');
        }
    }
    $.ajax({
        url: "/extendpage/action/datasave.aspx?entity=" + const_EditEntity + "&field=" + field + "&value=" + value + "&flag=1&action=singleupdate",
        type: "post",
        data: { data: id },
        cache: false,
        success: function (text) {
            if (text == 1) {
                alert("数据保存成功!")
                fnClose();
            } else {
                alert(text);
                //alert("数据保存失败!")
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

var fnDelete = function () {
    fnRemove();
}

//数据删除
var fnRemove = function () {
    if (typeof (fnCustomRemove) != "undefined") {
        fnCustomRemove();
        return;
    }

    var rows = fnGetSelectedRows();
    if (rows.length > 0) {
        if (confirm("确定删除选中记录？")) {
            var ids = [];
            for (var i = 0, l = rows.length; i < l; i++) {
                var r = rows[i];
                ids.push(r[const_entityID]);
            }
            var id = ids.join(',');
            grid.loading("操作中，请稍后......");
            $.ajax({
                url: "/extendpage/action/mdatasave.aspx?entity=" + const_EditEntity + "&action=delete&id=" + id,
                success: function (text) {
                    if (text == 1) {
                        alert("删除成功!");
                    }
                    grid.reload();
                },
                error: function () {
                }
            });
        }
    } else {
        alert("请选中一条记录");
    }
}

/**/
var fnAudit = function () {
    if (typeof (fnCustomAudit) != "undefined") {
        fnCustomAudit();
        return;
    }
}

//退回
var fnReturn = function () {
    if (typeof (fnCustomReturn) != "undefined") {
        fnCustomReturn();
        return;
    }
}

///导出
var fnOutput = function () {
    if (typeof (fnCustomOutput) == "undefined") {
        fnCustomOutput();
        return;
    }
}

var fnExport = function () {
    if (typeof (fnCustomExport) != "undefined") {
        fnCustomExport();
        return;
    }
    window.open(grid.url.replace(/&datagrid=true/g, "") + "&type=3");
}


/*
数据窗口编辑的保存
*/
var fnGridSave = function () {
    if (typeof (fnCustomGridSave) != "undefined") {
        fnCustomGridSave();
        return;
    }

    var data = grid.getChanges();
    var json = mini.encode(data);

    ///数据检查
    if (typeof (fnCustomGridDataCheck) != "undefined") {
        var msg = fnCustomGridDataCheck(data);
        if (msg != "") {
            alert(msg);
            return;
        }
    }

    grid.loading("保存中，请稍后......");
    $.ajax({
        url: "/extendpage/action/mdatasave.aspx?entity=" + const_EditEntity + "&action=batch&flag=1",
        data: { data: json },
        type: "post",
        success: function (text) {
            grid.reload();
            alert("批量保存成功!");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}



///快速定位
function QuickSearch() {
    var goodsinfo = mini.get("search").getValue();
    var rows = grid_t.findRows(function (row) {
        var goodsid = row.GOODSID;
        var goodscode = row.GOODSCODE;
        var brand = row.BRAND;
        var goodssname = row.GOODSSNAME;

        if (goodsid.match(goodsinfo) || goodscode.match(goodsinfo) || brand.match(goodsinfo) || goodssname.match(goodsinfo))
            return true;
        return false;
    });
    grid_t.scrollIntoView(rows[0]);
    grid_t.select(rows[0], false);
}


var fnEditMaster = function () {
    if (typeof (fnCustomEditMaster) != "undefined") {
        fnCustomEditMaster();
        return;
    }
}

var fnAddMaster = function () {
    if (typeof (fnCustomAddMaster) != "undefined") {
        fnCustomAddMaster();
        return;
    }
    fnInitData();
}

function fnInitData() {
    mini.prompt("表名或视图名：", "请输入",
            function (action, value) {
                if (action == "ok") {
                    fnRunProc2("usp_init_datagrid_setting", value + "," + value);
                }
            }
   );
}

//----------数据窗口相关事件-------------------------------------/
//单击单元格
var fnCellClick = function (e) {
    //alert("");
    if (typeof (fnCustomCellClick) != "undefined") {
        fnCustomCellClick(e);
        //return;
    }
}
//单击事件
var fnRowClick = function (e) {
    if (typeof (fnCustomRowClick) != "undefined") {
        fnCustomRowClick(e);
        //return;
    }
}
//双击事件
var fnDBRowClick = function (e) {
    if (typeof (fnCustomDBRowClick) != "undefined") {
        fnCustomDBRowClick(e);
        return;
    }
    //fnEdit();
}

//$(function () {
if (grid) {
    //alert(grid);
    grid.on("rowclick", fnRowClick);
    grid.on("rowdblclick", fnDBRowClick)
    grid.on("cellclick", fnCellClick)
}
//})();
/************************************************************************/


///往Grid里增加新行
var fnAddNewRow = function () {
    var newRow = {};
    grid.addRow(newRow, 0);

}



/*--------------------
动态加载脚本
---------------------*/
var fnLoadJSScript = function (url) {
    if (typeof ($) != "undefined") {
        $.getScript(url, function (response, status) { });
    } else {
        loadJS(url);
    }
}


//加载JS
var loadJS = function (src, charset, callback) {
    var head = document.getElementsByTagName("head")[0];

    var script = document.createElement('script');

    script.onload = script.onreadystatechange = script.onerror = function () {
        if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;

        script.onload = script.onreadystatechange = script.onerror = null;
        script.src = '';
        script.parentNode.removeChild(script);
        script = null;
        if (typeof (callback) == "undefined") {
            callback();
        }
    };

    script.charset = charset || document.charset || document.characterSet || 'gb2312';
    script.src = src;

    try {
        head.appendChild(script);
    } catch (exp) { }
};



//获取URL querystring parameter
function getPar1(source, name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(source)) return RegExp.$2; return "";
}

function getPar(name) {
    var _url = "http://" + document.location;
    return getPar1(_url, name);
}

